const {validationResult, buildCheckFunction} = require('express-validator')
const {isValidObjectId} = require('mongoose')

exports = module.exports = validations => {
  return async (req, res, next) => {
    await Promise.all(validations.map(validation => validation.run(req)))
    const errors = validationResult(req)
    if (errors.isEmpty()) {
      return next()
    }
    var errArr = errors.array()
    var filterErrors = ''
    if (errArr.length > 0) {
      filterErrors = errArr.reduce((prev, cur, index) => {
        return prev + cur.msg + ((index !== errArr.length - 1) ? ',' : '');
      }, '')
    } else {
      filterErrors = '传参错误'
    }
    res.status(422).json({errors: filterErrors})
  }
}

exports.isValidObjectId = (location, fields) => {
  return buildCheckFunction(location)(fields).custom(async value => {
    if (!isValidObjectId(value)) {
      return Promise.reject('ID 不是一个有效的 ObjectID')
    }
  })
}
